'''
Created on May 29, 2009

@author: mkiyer
'''

import cogent.parse.fasta

class SequenceFileGrabber(object):
    
    def __init__(self, fhd):        
        self.fhd = fhd
        self.name = fhd.readline()
        self.nameOffset = fhd.tell()
        # determine line width
        testline = fhd.readline()
        # TODO: assumes all lines are the same width
        self.lineSize = len(testline) - 1
        # TODO: get number of newline characters at end of each line, assume 1 for now

        print 'name', self.name
        print 'nameOffset', self.nameOffset
        print 'lineSize', self.lineSize

    def getSeq(self, start, end):        
        # calculate the position in the file to start reading
        # skip the header line and factor in the correct number of newline 
        # characters leading up to this sequence
        seq_start = self.nameOffset + int(start/self.lineSize) + start
        # calculate the size of the string to read
        read_size = (end + int(end/self.lineSize)) - (start + int(start/self.lineSize))
        # seek to the starting position and read the string
        self.fhd.seek(seq_start)
        raw_seq = self.fhd.read(read_size)
        # get rid of newlines
        seq = raw_seq.replace('\n','')
        return seq